package cc.autoapi.pucong.auto.flow.provider.log.manager;


import cc.autoapi.pucong.auto.flow.persistence.po.log.ApiInstancePo;
import cc.autoapi.pucong.auto.flow.persistence.repository.log.ApiInstanceService;
import cc.autoapi.pucong.auto.flow.persistence.utils.jdbc.BasePageVo;
import cc.autoapi.pucong.auto.flow.persistence.utils.jdbc.ExeRunSqlResultPage;
import cc.autoapi.pucong.auto.flow.provider.log.entity.ApiInstanceConvert;
import cc.autoapi.pucong.auto.flow.provider.log.entity.qo.ApiInstanceQo;
import cc.autoapi.pucong.auto.flow.provider.log.entity.vo.ApiInstanceDetailVo;
import cc.autoapi.pucong.auto.flow.provider.log.entity.vo.ApiInstanceVo;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author pucong
 * @description 项目api实例 managerService 实现类
 * @create 2024-10-07
 */
@Service
@Slf4j
public class ApiInstanceManager {

    @Resource
    private ApiInstanceService apiInstanceService;

    public BasePageVo<ApiInstanceVo> queryByPage(int pageNum, int pageSize, ApiInstanceQo qo) {
        ExeRunSqlResultPage<ApiInstancePo> pages = apiInstanceService.page(pageNum, pageSize, qo.getApiId(), qo.getExeStartTime(), qo.getExeEndTime(), qo.getExeStatus());
        BasePageVo<ApiInstancePo> execResultMapPage = pages.getExecResultMapPage();
        List<ApiInstanceVo> apiInstanceVos = ApiInstanceConvert.INSTANCE.po2vos(execResultMapPage.getRecords());

        BasePageVo<ApiInstanceVo> pageVo = new BasePageVo<>(pageSize, pageNum);
        pageVo.setPages(execResultMapPage.getPages());
        pageVo.setTotal(execResultMapPage.getTotal());
        pageVo.setRecords(apiInstanceVos);
        return pageVo;
    }

    public ApiInstanceDetailVo getDetailById(String id) {
        ApiInstancePo apiInstance = apiInstanceService.getById(id);
        ApiInstanceDetailVo apiInstanceVo = ApiInstanceConvert.INSTANCE.po2Detailvo(apiInstance);
        if (apiInstanceVo.getExeStartTime() != null && apiInstanceVo.getExeEndTime() != null) {
            String time = DateUtil.formatBetween(apiInstance.getExeStartTime(), apiInstance.getExeEndTime());
            apiInstanceVo.setExeTime(time);
        }
        return apiInstanceVo;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean batchDeleteByIds(List<String> ids) {
        Boolean i = apiInstanceService.removeBatchByIds(ids);
        return i;
    }
}
